package com.woniuxy.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.woniuxy.core.exception.WoniuxyException;
import com.woniuxy.core.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class GateWayGloalbleExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable e) {
        Result<?> res = null;
        if(e instanceof WoniuxyException) {
            WoniuxyException we = (WoniuxyException)e;
             res = Result.fail(we.getCode(), we.getMessage());
        } else if(e instanceof Exception) {
            res = Result.fail(500, "系统异常");
        }
        String jsonStr = JSONUtil.parse(res).toString();
        log.error("出现异常:{}==="+jsonStr);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            return exchange.getResponse().bufferFactory().wrap(jsonStr.getBytes());
        }));
    }
}
